import React, {Component} from 'react'
import './App.css'
// 导入自定义组件
import Header from './components/Header'
import List from './components/List'
import Footer from './components/Footer'

/* 
    这次的案例是一个综合的小项目：日记本
    根据静态页面拆分出四个组件，需要注意的主要是父子组件之间的相互通信

*/
export default class App extends Component {

    state = {todoList:[
        {id:'001',title:'睡觉',finished:false},
        {id:'002',title:'学习',finished:true},
        {id:'003',title:'写代码',finished:false},
    ]}

    // 添加新的任务
    addTodo = (todoObj)=>{
        const {todoList} = this.state; 
        const newTodoList = [todoObj,...todoList]
        this.setState({todoList:newTodoList})
    }

    // 更新任务状态
    updateTodo = (id,isFinished)=>{
        const {todoList} = this.state;
        const newTodoList = todoList.map(item => {
            if(item.id === id){
                return {...item,finished:isFinished}
            }else{
                return item
            }
        })
        this.setState({todoList:newTodoList})
    }

    // 删除选中（已完成）的任务
    deleteTodo = (id)=>{
        const {todoList} = this.state;
        // 留下还未完成的任务
        const newTodoList = todoList.filter((todoObj)=>{
            return todoObj.id !== id;
        })
        this.setState({todoList:newTodoList});
    }

    // 选中/不选中所有方法
    selectAll = (finished) => {
        const {todoList} = this.state;
        const newTodoList = todoList.map((todoObj) => {
            return {...todoObj,finished}
        })
        this.setState({todoList:newTodoList})
    }

    // 删除所有选中(已完成)任务
    deleteAllSelected = () => {
       const {todoList} = this.state;
       const newTodoList = todoList.filter((todoObj)=>{
        return !todoObj.finished
       })
       this.setState({todoList:newTodoList})
    }


    render() {
        const {todoList} = this.state;
        return (
            <div className="todo-container">
                <div className="todo-wrap">
                    <Header addTodo={this.addTodo} />
                    <List deleteTodo={this.deleteTodo} updateTodo={this.updateTodo} todoList={todoList} />
                    <Footer deleteAllSelected={this.deleteAllSelected} selectAll={this.selectAll}  todoList={todoList}/>
                </div>
            </div>
        )
    }
}